#include "CEngineCore.h"

#include "Core\CWindow.h"
#include "Render\CRenderSystem.h"
#include "D3D9\CD3D9RenderSystem.h"
#include "D3D11\CD3D11RenderSystem.h"
#include "Core\CChrono.h"
#include "Core\CInput.h"

namespace Nervus {
	namespace Core {
		//----------------------------------------------------------------------------------
		EngineCore::EngineCore()
			: mRenderSystem(Render::NERVUS_RS_D3D9), mUpdateFreq(30), mRenderFreq(-1),
			mRenderer(NULL), mIsRunning(false)
		{
			mMainWnd = new Window();
		}
		//----------------------------------------------------------------------------------
		EngineCore::~EngineCore(){
			delete mChrono;

			delete mRenderer;
			delete mMainWnd;
			
			//"Kills" current WinAPI thread
			PostQuitMessage(1);
		}
		//----------------------------------------------------------------------------------
		void EngineCore::setWindowParams(string title, u32 posX, u32 posY, u32 width, u32 height){
			mMainWnd->setWindowTitle(title);
			mMainWnd->setWindowSize(width, height);
			mMainWnd->setWindowPos(posX, posY);
		}
		//----------------------------------------------------------------------------------
		void EngineCore::setRendererParams(Render::NERVUS_RENDERSYSTEM renderer, bool fs){
			mRenderSystem = renderer;
		}
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------
		void EngineCore::runEngine(){
			if (!mMainWnd->launchWindow()){
				//
				return;
			}


			switch (mRenderSystem){
				case Render::NERVUS_RS_D3D9:
					mRenderer = new Render::D3D9RenderSystem(mMainWnd);
					break;
				case Render::NERVUS_RS_D3D11:
					mRenderer = new Render::D3D11RenderSystem(mMainWnd);
					break;
			}
			if (!mRenderer->launchRenderSystem()){
				//
				return;
			}

			mInput = mMainWnd->getInput();
			mChrono = new Chrono();




			initEngine();


			while (!mMainWnd->isClosed()){
				if (!mMainWnd->processWindow()){


					if (mChrono->tickEveryMilis(1000 / mUpdateFreq)){
						mMainWnd->getInput()->updateInput();
						updateEngine();
					}




					mRenderer->beginRender();
					renderEngine();
					mRenderer->endRender();




				}
			}
		}
		//----------------------------------------------------------------------------------
	}
}